﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Globalization;
using SWCInvoice.Model;
using GalaSoft.MvvmLight;
using SWCInvoice.Servicelayer;
using System.Windows.Input;
using System.Windows;
using Ookii.Dialogs.Wpf;
using SWCInvoice.Utils;
using System.IO;
using AvalonDock;
using SWCInvoice.Returntyps;
using System.Net;
using UpdateLib.Utils;
using UpdateLib.Model;

namespace SWCInvoice.ViewModel {
    public class MainViewModel : ViewModelBase {

        #region Fields

        /// <summary>
        /// The backstage view model
        /// </summary>
        BackstageViewModel _backstageViewModel;
        
        /// <summary>
        /// The culture view model
        /// </summary>
        CultureViewModel _cultureViewModel;

        /// <summary>
        /// The preview settings view model
        /// </summary>
        PreviewSettingsViewModel _previewSettingsViewModel;
        
        /// <summary>
        /// The identifier view model
        /// </summary>
        IdentifierViewModel _identifierViewModel;
        /// <summary>
        /// The virtual document structure view model
        /// </summary>
        VirtualDocumentStructureViewModel _virtualDocumentStructureViewModel;
        /// <summary>
        /// The message view model
        /// </summary>
        MessageViewModel _messageViewModel;
        /// <summary>
        /// The pdf view view model
        /// </summary>
        PdfViewViewModel _pdfViewViewModel;
        /// <summary>
        /// The logging manager
        /// </summary>
        LoggingManager _loggingManager;

        private RelayCommand _SetIdentifierCommand;
        private RelayCommand _DeleteIdentifierCommand;
        private RelayCommand _SplitDocumentCommand;
        private RelayCommand _SortDocumentTestCommand;
        private RelayCommand _MergeDocumentsCommand;
        private RelayCommand _AddPageOddCommand;
        private RelayCommand _AddPageEvenCommand;
        private RelayCommand _AddPageBothCommand;
        private RelayCommand _HelpCommand;
        private RelayCommand _PinToDesktopCommand;
        private RelayCommand _MessageViewCommand;
        private RelayCommand _LogViewCommand;
        private RelayCommand _VDSExplorerViewCommand;
        private RelayCommand _PreviewCommand;
        private RelayCommand _SaveCommand;
        private RelayCommand _SaveAsCommand;
        private RelayCommand _OpenPDFCommand;
        private RelayCommand _CloseCommand;
        private RelayCommand _ExitCommand;
        private RelayCommand _SetTempViewPathNameCommand;
        private RelayCommand _OpenInputDialogCommand;
        private RelayCommand _AddMessageCommand;
        private RelayCommand _ClearMessageQueueCommand;
        private RelayCommand _CheckForUpdateCommand;

        private MainWindow _mainWindow;
        private Windows.Help _helpWindow;
        private Windows.LogView _logWindow;
        private VirtualDocumentStructureView _vdsExplorerWindow;
        private Windows.MessageView _messageWindow;
        private Windows.PdfView _pdfViewWindow;
        private Windows.InputDialog _inputDialog;

        #endregion

        #region Properties

        /// <summary>
        /// The backstage view model
        /// </summary>
        public BackstageViewModel BackstageViewModel {
            get {
                return _backstageViewModel;
            }
        }

        /// <summary>
        /// The culture view model
        /// </summary>
        public CultureViewModel CultureViewModel
        {
            get
            {
                return _cultureViewModel;
            }
        }


        /// <summary>
        /// The preview settings view model
        /// </summary>
        public PreviewSettingsViewModel PreviewSettingsViewModel
        {
            get
            {
                return _previewSettingsViewModel;
            }
        }

        /// <summary>
        /// The identifier view model
        /// </summary>
        public IdentifierViewModel IdentifierViewModel {
            get {
                return _identifierViewModel;
            }
        }

        /// <summary>
        /// The message view model
        /// </summary>
        public MessageViewModel MessageViewModel {
            get {
                return _messageViewModel;
            }
        }

        /// <summary>
        /// The virtual document structure view model
        /// </summary>
        public VirtualDocumentStructureViewModel VirtualDocumentStructureViewModel {
            get {
                return _virtualDocumentStructureViewModel == null ? _virtualDocumentStructureViewModel = new VirtualDocumentStructureViewModel() : _virtualDocumentStructureViewModel;
            }
        }

        /// <summary>
        /// The page view view model
        /// </summary>
        public PdfViewViewModel PdfViewViewModel
        {
            get
            {
                return _pdfViewViewModel;
            }
        }

        /// <summary>
        /// The logging manager
        /// </summary>
        public LoggingManager LoggingManager {
            get {
                return _loggingManager;
            }     
        }

        /// <summary>
        /// Version information
        /// </summary>
        public string Version {
            get {
                Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                return string.Format(Properties.ResourceMain.InformationVersion, version.Major, version.Minor, version.Revision, version.Build);
            }
        }

        #region Commands

        public RelayCommand SetIdentifierCommand
        {
            get
            {
                if (_SetIdentifierCommand == null)
                    _SetIdentifierCommand = new RelayCommand(param => SetIdentifier(param));
                return _SetIdentifierCommand;
            }
        }

        public RelayCommand DeleteIdentifierCommand
        {
            get
            {
                if (_DeleteIdentifierCommand == null)
                    _DeleteIdentifierCommand = new RelayCommand(param => DeleteIdentifier());
                return _DeleteIdentifierCommand;
            }
        }

        
        public RelayCommand SortDocumentTestCommand
        {
            get
            {
                if (_SortDocumentTestCommand == null)
                    _SortDocumentTestCommand = new RelayCommand(param => SortDocument());
                return _SortDocumentTestCommand;
            }
        }


        public RelayCommand SplitDocumentCommand
        {
            get
            {
                if (_SplitDocumentCommand == null)
                    _SplitDocumentCommand = new RelayCommand(param => SplitDocument());
                return _SplitDocumentCommand;
            }
        }

        public RelayCommand MergeDocumentsCommand
        {
            get
            {
                if (_MergeDocumentsCommand == null)
                    _MergeDocumentsCommand = new RelayCommand(param => MergeDocuments());
                return _MergeDocumentsCommand;
            }
        }

        public RelayCommand AddPageOddCommand
        {
            get
            {
                if (_AddPageOddCommand == null)
                    _AddPageOddCommand = new RelayCommand(param => AddPageOdd());
                return _AddPageOddCommand;
            }
        }

        public RelayCommand AddPageEvenCommand
        {
            get
            {
                if (_AddPageEvenCommand == null)
                    _AddPageEvenCommand = new RelayCommand(param => AddPageEven());
                return _AddPageEvenCommand;
            }
        }

        public RelayCommand AddPageBothCommand
        {
            get
            {
                if (_AddPageBothCommand == null)
                    _AddPageBothCommand = new RelayCommand(param => AddPageBoth());
                return _AddPageBothCommand;
            }
        }

        
        public RelayCommand VDSExplorerViewCommand
        {
            get
            {
                if (_VDSExplorerViewCommand == null)
                    _VDSExplorerViewCommand = new RelayCommand(param => VDSExplorerView());
                return _VDSExplorerViewCommand;
            }
        }

        public RelayCommand LogViewCommand
        {
            get
            {
                if (_LogViewCommand == null)
                    _LogViewCommand = new RelayCommand(param => LogView());
                return _LogViewCommand;
            }
        }

        public RelayCommand MessageViewCommand
        {
            get
            {
                if (_MessageViewCommand == null)
                    _MessageViewCommand = new RelayCommand(param => MessageView());
                return _MessageViewCommand;
            }
        }

        public RelayCommand HelpCommand
        {
            get
            {
                if (_HelpCommand == null)
                    _HelpCommand = new RelayCommand(param => Help(param));
                return _HelpCommand;
            }
        }

        public RelayCommand PinToDesktopCommand 
        {
            get {
                if (_PinToDesktopCommand == null)
                    _PinToDesktopCommand = new RelayCommand(param => PinToDesktop());
                return _PinToDesktopCommand;
            }
        }

        public RelayCommand PreviewCommand
        {
            get
            {
                if (_PreviewCommand == null)
                    _PreviewCommand = new RelayCommand(param => Preview());
                return _PreviewCommand;
            }
        }

        public RelayCommand SaveCommand
        {
            get
            {
                if (_SaveCommand == null)
                    _SaveCommand = new RelayCommand(param => Save());
                return _SaveCommand;
            }
        }

        public RelayCommand SaveAsCommand
        {
            get
            {
                if (_SaveAsCommand == null)
                    _SaveAsCommand = new RelayCommand(param => SaveAs());
                return _SaveAsCommand;
            }
        }

        public RelayCommand OpenPDFCommand
        {
            get
            {
                if (_OpenPDFCommand == null)
                    _OpenPDFCommand = new RelayCommand(param => OpenPDF());
                return _OpenPDFCommand;
            }
        }

        public RelayCommand CloseCommand
        {
            get
            {
                if (_CloseCommand == null)
                    _CloseCommand = new RelayCommand(param => Close());
                return _CloseCommand;
            }
        }

        public RelayCommand ExitCommand
        {
            get
            {
                if (_ExitCommand == null)
                    _ExitCommand = new RelayCommand(param => Exit());
                return _ExitCommand;
            }
        }

        public RelayCommand SetTempViewPathNameCommand
        {
            get
            {
                if (_SetTempViewPathNameCommand == null)
                    _SetTempViewPathNameCommand = new RelayCommand(param => SetTempViewFolder());
                return _SetTempViewPathNameCommand;
            }
        }

        public RelayCommand OpenInputDialogCommand
        {
            get
            {
                if (_OpenInputDialogCommand == null)
                    _OpenInputDialogCommand = new RelayCommand(param => OpenInputDialog(param));
                return _OpenInputDialogCommand;
            }
        }

        public RelayCommand AddMessageCommand {
            get {
                if (_AddMessageCommand == null)
                    _AddMessageCommand = new RelayCommand(param => AddMessage(param));
                return _AddMessageCommand;
            }
        }

        public RelayCommand ClearMessageQueueCommand {
            get {
                if (_ClearMessageQueueCommand == null)
                    _ClearMessageQueueCommand = new RelayCommand(param => ClearMessageQueue());
                return _ClearMessageQueueCommand;
            }
        }


        public RelayCommand CheckForUpdateCommand {
            get {
                if (_CheckForUpdateCommand == null)
                    _CheckForUpdateCommand = new RelayCommand(param => CheckForUpdate());
                return _CheckForUpdateCommand;
            }
        }



        #endregion

        #region Windows

        /// <summary>
        /// The Main Window
        /// </summary>
        public MainWindow MainWindow
        {
            get
            {
                return _mainWindow;
            }

            set 
            {
                _mainWindow = value;    
            }
        }

        /// <summary>
        /// The Help Window
        /// </summary>
        public Windows.Help HelpWindow
        {
            get
            {
                return _helpWindow;
            }
        }

        /// <summary>
        /// The PdfView Window
        /// </summary>
        public Windows.PdfView PdfViewWindow
        {
            get
            {
                return _pdfViewWindow;
            }
        }

        
        #endregion

        #endregion

        public MainViewModel() {
            _loggingManager = new Utils.LoggingManager(this);


            _identifierViewModel = new ViewModel.IdentifierViewModel();
            //_identifierViewModel.Identifiers = SWCInvoiceSettings.GetIdentifierSettings();
            _identifierViewModel.Identifiers = FilterHandler.GetFilter(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\filters.xml");

            _pdfViewViewModel = new ViewModel.PdfViewViewModel();

            _backstageViewModel = new ViewModel.BackstageViewModel();
           
            _backstageViewModel.Culture = SWCInvoiceSettings.GetCultureInfo();
            
            _backstageViewModel.TemporaryViewPath = SWCInvoiceSettings.GetTemporaryViewPath();
            _backstageViewModel.BasicResultPathName = SWCInvoiceSettings.GetBasicResultPathName();
            _backstageViewModel.SessionPathName = SWCInvoiceSettings.GetSessionPathName();
            _backstageViewModel.MergePathName = SWCInvoiceSettings.GetMergePathName();
            _backstageViewModel.DocumentsPathName = SWCInvoiceSettings.GetDocumentsPathName();

            _backstageViewModel.PreviewImageFormat = SWCInvoiceSettings.GetPreviewImageFormat();
            _backstageViewModel.PreviewImageDpi = SWCInvoiceSettings.GetPreviewImageDpi();
            _backstageViewModel.PreviewImageAntiAliasMode = SWCInvoiceSettings.GetPreviewImageAntiAliasMode();

            try { _backstageViewModel.ProxyUse = bool.Parse(SWCInvoiceSettings.GetProxyUseFlag()); } catch { _backstageViewModel.ProxyUse = false; }
            _backstageViewModel.Proxy = SWCInvoiceSettings.GetProxyFlag();
            _backstageViewModel.Domain = SWCInvoiceSettings.GetDomainFlag();
            _backstageViewModel.User = SWCInvoiceSettings.GetUserFlag();
            _backstageViewModel.Password = SWCInvoiceSettings.GetPasswordFlag();


            _cultureViewModel = new ViewModel.CultureViewModel();
            _previewSettingsViewModel = new PreviewSettingsViewModel();

            _messageViewModel = new MessageViewModel();

            SWCInvoiceSettings.GetCultureInfo();
            _cultureViewModel.Cultures.Add(new Culture("en-US", "..\\icons\\gui\\unitedStatesOfAmerica.png"));
            _cultureViewModel.Cultures.Add(new Culture("dsb-DE", "..\\icons\\gui\\lowerSorbian.png"));
            _cultureViewModel.Cultures.Add(new Culture("hsb-DE", "..\\icons\\gui\\upperSorbian.png"));
            _cultureViewModel.Cultures.Add(new Culture("de-DE","..\\icons\\gui\\germany.png"));
                          

            _previewSettingsViewModel.PreviewImageFormats.Add(new ImageFormatWrapper(Cyotek.GhostScript.ImageFormat.Bitmap24));
            _previewSettingsViewModel.PreviewImageFormats.Add(new ImageFormatWrapper(Cyotek.GhostScript.ImageFormat.Bitmap8));
            _previewSettingsViewModel.PreviewImageFormats.Add(new ImageFormatWrapper(Cyotek.GhostScript.ImageFormat.BitmapMono));
            _previewSettingsViewModel.PreviewImageFormats.Add(new ImageFormatWrapper(Cyotek.GhostScript.ImageFormat.Jpeg));
            _previewSettingsViewModel.PreviewImageFormats.Add(new ImageFormatWrapper(Cyotek.GhostScript.ImageFormat.Png24));
            _previewSettingsViewModel.PreviewImageFormats.Add(new ImageFormatWrapper(Cyotek.GhostScript.ImageFormat.Png8));
            _previewSettingsViewModel.PreviewImageFormats.Add(new ImageFormatWrapper(Cyotek.GhostScript.ImageFormat.PngMono));
            _previewSettingsViewModel.PreviewImageFormats.Add(new ImageFormatWrapper(Cyotek.GhostScript.ImageFormat.Tiff24));
            _previewSettingsViewModel.PreviewImageFormats.Add(new ImageFormatWrapper(Cyotek.GhostScript.ImageFormat.TiffMono));
            _previewSettingsViewModel.PreviewImageFormats.Add(new ImageFormatWrapper(Cyotek.GhostScript.ImageFormat.Unknown));

            _previewSettingsViewModel.PreviewImageDPIs.Add(50);
            _previewSettingsViewModel.PreviewImageDPIs.Add(100);
            _previewSettingsViewModel.PreviewImageDPIs.Add(200);
            _previewSettingsViewModel.PreviewImageDPIs.Add(300);
            _previewSettingsViewModel.PreviewImageDPIs.Add(400);

            _previewSettingsViewModel.PreviewImageAntiAliasModes.Add(new AntiAliasModeWrapper(Cyotek.GhostScript.AntiAliasMode.High));
            _previewSettingsViewModel.PreviewImageAntiAliasModes.Add(new AntiAliasModeWrapper(Cyotek.GhostScript.AntiAliasMode.Medium));
            _previewSettingsViewModel.PreviewImageAntiAliasModes.Add(new AntiAliasModeWrapper(Cyotek.GhostScript.AntiAliasMode.Low));
            _previewSettingsViewModel.PreviewImageAntiAliasModes.Add(new AntiAliasModeWrapper(Cyotek.GhostScript.AntiAliasMode.None));
        }
       

        #region Command Methods

        #region Views

        /// <summary>
        /// Open the VDS Explorer Window
        /// </summary>
        private void VDSExplorerView() {
            _vdsExplorerWindow = new VirtualDocumentStructureView();

            //ToolBoxContent
            DockableContent newContent = new DockableContent();
            //TabContent
            //DocumentContent newContent = new DocumentContent();

            DockableContent existingContent = GetContentByName("virtualDocumentStructureView");
            if (existingContent == null) {
                newContent.Title = Properties.ResourceVirtualDocumentStructureView.WindowTitle;
                newContent.Name = "virtualDocumentStructureView";
                newContent.Content = _vdsExplorerWindow;

                newContent.Show(MainWindow.dockingManager);
                newContent.Activate();
            } else if (existingContent.State == DockableContentState.Hidden) {
                existingContent.Show(MainWindow.dockingManager);
                existingContent.Activate(); 
            } else {
                existingContent.Activate();            
            }

        }

        /// <summary>
        /// Open the Log Window
        /// </summary>
        private void LogView() {
            _logWindow = new Windows.LogView();

            //ToolBoxContent
            DockableContent newContent = new DockableContent();
            //TabContent
            //DocumentContent newContent = new DocumentContent();

            DockableContent existingContent = GetContentByName("logView");
            if (existingContent == null) {
                newContent.Title = Properties.ResourceLog.WindowTitle;
                newContent.Name = "logView";
                newContent.Content = _logWindow;

                newContent.Show(MainWindow.dockingManager);
                newContent.Activate();
            } else if (existingContent.State == DockableContentState.Hidden) {
                existingContent.Show(MainWindow.dockingManager);
                existingContent.Activate();
            } else {
                existingContent.Activate();
            }
        }

        /// <summary>
        /// Open the Message Window
        /// </summary>
        private void MessageView() {
            _messageWindow = new Windows.MessageView();

            //ToolBoxContent
            DockableContent newContent = new DockableContent();
            //TabContent
            //DocumentContent newContent = new DocumentContent();

            DockableContent existingContent = GetContentByName("messagesView");
            if (existingContent == null) {
                newContent.Title = Properties.ResourceMessages.WindowTitle;
                newContent.Name = "messagesView";
                newContent.Content = _messageWindow;

                newContent.Show(MainWindow.dockingManager);
                newContent.Activate();
            } else if (existingContent.State == DockableContentState.Hidden) {
                existingContent.Show(MainWindow.dockingManager);
                existingContent.Activate();
            } else {
                existingContent.Activate();
            }
        }

        /// <summary>
        /// Open the Help Window
        /// </summary>
        /// <param name="param"></param>
        private void Help(object param) {
            string parameters = (string)param;

            if(!string.IsNullOrWhiteSpace(parameters))
                _helpWindow = new Windows.Help(parameters);
            else
                _helpWindow = new Windows.Help();

            //ToolBoxContent
            DockableContent newContent = new DockableContent();
            //TabContent
            //DocumentContent newContent = new DocumentContent();

            DockableContent existingContent = GetContentByName("helpView");
            if (existingContent == null) {
                newContent.Title = Properties.ResourceHelp.WindowTitle;
                newContent.Name = "helpView";
                newContent.Content = _helpWindow;

                newContent.Show(MainWindow.dockingManager);
                newContent.Activate();
            } else if (existingContent.State == DockableContentState.Hidden) {
                existingContent.Content = _helpWindow;
                existingContent.Show(MainWindow.dockingManager);
                existingContent.Activate();
            }
            else {
                existingContent.Activate();
            }
        }

        /// <summary>
        /// Pin or UnPin the Window to the Screen
        /// </summary>
        private void PinToDesktop() {
            _mainWindow.Topmost = !_mainWindow.Topmost; 
        }

        /// <summary>
        /// Open the Preview Window
        /// </summary>
        private void Preview() {
            _pdfViewWindow = new Windows.PdfView();

            //ToolBoxContent
            DockableContent newContent = new DockableContent();
            //TabContent
            //DocumentContent newContent = new DocumentContent();

            DockableContent existingContent = GetContentByName("rightToolBoxView");
            if (existingContent == null) {
                newContent.Title = Properties.ResourcePdfView.WindowTitle;
                newContent.Name = "rightToolBoxView";
                newContent.Content = _pdfViewWindow;


                newContent.Show(MainWindow.dockingManager);
                //dockingManager.Show(newContent);
                newContent.Activate();
            } else if (existingContent.State == DockableContentState.Hidden) {
                existingContent.Show(MainWindow.dockingManager);
                existingContent.Activate();
            } else {
                existingContent.Activate();
            }
            //dockingManager.Show(existingContent);
        }

        #endregion

        /// <summary>
        /// Add a new message in the message queue
        /// </summary>
        /// <param name="param">Message object</param>
        private void AddMessage(object param) {            
            try {
                if(!string.IsNullOrWhiteSpace(((Message)param).Title))
                    LoggingManager.AddMessage((Message)param);        
            } catch (Exception ex) {
                
                
            }            
        }

        /// <summary>
        /// Clear the message queue
        /// </summary>
        private void ClearMessageQueue() {
            LoggingManager.ClearMessageQueue();
        }

        /// <summary>
        /// Check for updates:
        /// Get the running version - compare the versions - start the updater 
        /// </summary>
        private void CheckForUpdate() {

            bool isPoxy = bool.Parse(SWCInvoiceSettings.GetProxyUseFlag());
            UpdateInfo _updateInfo = null;

            if (isPoxy)
                _updateInfo = UpdateLib.Utils.Utils.CheckForUpdates(SWCInvoiceSettings.GetUpdateUrlFlag(), SWCInvoiceSettings.GetProxyFlag(), SWCInvoiceSettings.GetDomainFlag(), SWCInvoiceSettings.GetUserFlag(), SWCInvoiceSettings.GetPasswordFlag());
            else
                _updateInfo = UpdateLib.Utils.Utils.CheckForUpdates(SWCInvoiceSettings.GetUpdateUrlFlag());

            Version curVersionHelp = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            Version curVersionLib = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            Version curVersionConf = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            Version curVersionApp = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            if ((curVersionLib.CompareTo(_updateInfo.LibVersion) < 0) ||
                (curVersionHelp.CompareTo(_updateInfo.HelpVersion) < 0) ||
                (curVersionConf.CompareTo(_updateInfo.ConfVersion) < 0) ||
                (curVersionApp.CompareTo(_updateInfo.AppVersion) < 0)
                ) {

                string title = "New version detected.";
                string message = "Download the new version?";

                if (System.Windows.MessageBoxResult.Yes ==
                MessageBox.Show(message, title,
                                System.Windows.MessageBoxButton.YesNo,
                                System.Windows.MessageBoxImage.Question)) {

                    //Start the Updater
                    bool resultProcessStart = Utils.Utils.StartUpdater(curVersionLib.ToString(), curVersionHelp.ToString(), curVersionConf.ToString(), curVersionApp.ToString());

                    if (resultProcessStart)
                        _mainWindow.Close();
                }
            } else {
                string title = "Information";
                string message = "Your version is up to date.";

                MessageBox.Show(message, title,
                                System.Windows.MessageBoxButton.OK,
                                System.Windows.MessageBoxImage.Information);



            }
        }

        /// <summary>
        /// Set the identifier of the pages
        /// </summary>
        /// <param name="param"></param>
        private void SetIdentifier(object param) {            
            Identifier identifier = (Identifier)((Fluent.GalleryItem)(param)).Content;
           
            //Worker.SetPageIdentifier(_mainViewModel.CurrentIdentifier);            
            //PDFHandler.SetPageIdentifier(this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0], this.IdentifierViewModel.CurrentIdentifier.SearchKeyword, this.IdentifierViewModel.CurrentIdentifier.Expression, this.IdentifierViewModel.CurrentIdentifier.Inheritance);
            SetPageIdentifierInfo identifierInfo = PDFHandler.SetPageIdentifier(this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0], identifier.SearchKeyword, identifier.Expression, identifier.Inheritance, identifier.Additional);

            ClearMessageQueueCommand.Execute(null);
            AddMessageCommand.Execute(identifierInfo.GetMessage());

        }

        private void DeleteIdentifier() {
            DeletePageIdentifierInfo deletePageIdentifierInfo =  PDFHandler.DeletePageIdentifier(this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0]);

            ClearMessageQueueCommand.Execute(null);
            AddMessageCommand.Execute(deletePageIdentifierInfo.GetMessage());
        }

        private void SortDocument() {
            
            SetDocumentSortIdentifierInfo identifierInfo = PDFHandler.SetDocumentSortIdentifier(this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0], @"\n03[0-9]{3}\s[A-Za-z]*") ;

            ClearMessageQueueCommand.Execute(null);

            AddMessageCommand.Execute(identifierInfo.GetMessage());


        }

        private void SplitDocument() {
            SplitDocumentByIdentifierInfo splitDocumentByIdentifierInfo = null;
            
            ClearMessageQueueCommand.Execute(null);
            
            //Worker.SplitDocumentByIdentifier(_mainViewModel.VirtualDocumentStructures[0].Documents.ToList<Document>().Find( p => p.IsOriginal));
            if (VirtualDocumentStructureViewModel.VirtualDocumentStructures != null && VirtualDocumentStructureViewModel.VirtualDocumentStructures.Count > 0)
                splitDocumentByIdentifierInfo =  PDFHandler.SplitDocumentByIdentifier(this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0].Documents.ToList<Document>().Find(p => p.IsOriginal));

            AddMessageCommand.Execute(splitDocumentByIdentifierInfo.GetMessage());
        }

        private void MergeDocuments() {
            MergeDocumentsInfo mergeDocumentsInfo = null;

            ClearMessageQueueCommand.Execute(null);

            if (VirtualDocumentStructureViewModel.VirtualDocumentStructures != null && VirtualDocumentStructureViewModel.VirtualDocumentStructures.Count > 0)
                mergeDocumentsInfo = PDFHandler.MergeDocuments(this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0]);

            AddMessageCommand.Execute(mergeDocumentsInfo.GetMessage());
        }

        private void AddPageOdd() {
            ClearMessageQueueCommand.Execute(null);
            AddEmptyPageInfo addEmptyPageInfo = PDFHandler.AddEmptyPage(this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0], true, false);

            AddMessageCommand.Execute(addEmptyPageInfo.GetMessage());
        }

        private void AddPageEven() {
            ClearMessageQueueCommand.Execute(null);
            AddEmptyPageInfo addEmptyPageInfo = PDFHandler.AddEmptyPage(this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0], false, true);

            AddMessageCommand.Execute(addEmptyPageInfo.GetMessage());
        }

        private void AddPageBoth()  {
            ClearMessageQueueCommand.Execute(null);
            AddEmptyPageInfo addEmptyPageInfo = PDFHandler.AddEmptyPage(this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0], true, true);

            AddMessageCommand.Execute(addEmptyPageInfo.GetMessage());
        }

        

        /// <summary>
        /// Get existing dockable content
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The dockable content</returns>
        public DockableContent GetContentByName(string name) {
            return MainWindow.dockingManager.DockableContents.Where(dc => dc.Name == name).FirstOrDefault();
        }


        /// <summary>
        /// Take over the path names to the vds
        /// Use it before saving.
        /// The changes must be take over to all documents. 
        /// </summary>
        private void PreSaveAction()  {
            //Logging
            ClearMessageQueueCommand.Execute(null);

            foreach (VirtualDocumentStructure vdsItem in this.VirtualDocumentStructureViewModel.VirtualDocumentStructures) {
                string tmpVdsName = Path.GetFileNameWithoutExtension(vdsItem.FileName);
                vdsItem.BasicResultPathName = Utils.Utils.PathNameReplacer(_backstageViewModel.BasicResultPathName, tmpVdsName);
                vdsItem.SessionPathName = Utils.Utils.PathNameReplacer(_backstageViewModel.SessionPathName, tmpVdsName);
                vdsItem.MergePathName = Utils.Utils.PathNameReplacer(_backstageViewModel.MergePathName, tmpVdsName);
                vdsItem.DocumentsPathName = Utils.Utils.PathNameReplacer(_backstageViewModel.DocumentsPathName, tmpVdsName);

                foreach (Document documentItem in vdsItem.Documents) {
                    if(documentItem.IsMerged)
                        documentItem.DocumentPathName = vdsItem.MergePathName;
                    else if (documentItem.IsOriginal)
                        documentItem.DocumentPathName = string.Empty;
                    else
                        documentItem.DocumentPathName = vdsItem.DocumentsPathName;

                }    
            }
        }

        /// <summary>
        /// Build the result path structure and call the save method (create pdf)
        /// </summary>
        /// <param name="mainResultPath">base result path</param>
        private void SaveAction(string mainResultPath) {
            if (this.VirtualDocumentStructureViewModel != null && this.VirtualDocumentStructureViewModel.VirtualDocumentStructures.Count > 0) {
                VirtualDocumentStructure vds = this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0];

                ///create the subfolders
                string basicResultPath = _backstageViewModel.BasicResultPathName;
                string mainSessionPath = Utils.Utils.PathNameReplacer(_backstageViewModel.SessionPathName, Path.GetFileNameWithoutExtension(this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0].FileName));//string.Format(_backstageViewModel.SessionPathName, Path.GetFileNameWithoutExtension(this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[0].FileName));
                DirectoryInfo info_1 = Directory.CreateDirectory(mainResultPath + "\\" + vds.BasicResultPathName + "\\" + vds.SessionPathName + "\\" + vds.MergePathName);
                DirectoryInfo info_2 = Directory.CreateDirectory(mainResultPath + "\\" + vds.BasicResultPathName + "\\" + vds.SessionPathName + "\\" + vds.DocumentsPathName);

                //set result location
                vds.ResultFolderPath = mainResultPath + "\\" + vds.BasicResultPathName + "\\" + vds.SessionPathName + "\\";

                //save
                Worker.CreatePDF(vds, false);
            }
        }

        private void Save() {           
            PreSaveAction();

            string applicationPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            SaveAction(applicationPath);
        }

        private void SaveAs() {            
            PreSaveAction();

            VistaFolderBrowserDialog folderBrowserDialog = new VistaFolderBrowserDialog();
            folderBrowserDialog.ShowNewFolderButton = true;
            folderBrowserDialog.ShowDialog();

            if (!string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath)) {
                SaveAction(folderBrowserDialog.SelectedPath);                
            }
        }

        private void OpenPDF() {
            VistaOpenFileDialog openFileDialog = new VistaOpenFileDialog();
            openFileDialog.Multiselect = false;
            openFileDialog.DefaultExt = "pdf";

            openFileDialog.ShowDialog();
            if (openFileDialog.CheckFileExists && !string.IsNullOrWhiteSpace(openFileDialog.FileName)) {

                //Logging
                ClearMessageQueueCommand.Execute(null);

                Worker.ExtractPDF(openFileDialog.FileName);
            }
        }

        private void Close() {
            for (int i = this.VirtualDocumentStructureViewModel.VirtualDocumentStructures.Count - 1; i >= 0; i--) {
                this.VirtualDocumentStructureViewModel.VirtualDocumentStructures[i].Dispose();
                this.VirtualDocumentStructureViewModel.VirtualDocumentStructures.RemoveAt(i);
            }
            this.VirtualDocumentStructureViewModel.VirtualDocumentStructures = null;
            this.VirtualDocumentStructureViewModel.CurrentVirtualDocumentStructure = null;

            //Logging
            ClearMessageQueueCommand.Execute(null);
            AddMessageCommand.Execute(new Message(Properties.ResourceTextMessages.ClosePDFMessage, Enums.MessageTyp.Information, Properties.ResourceTextMessages.ClosePDFMessage));
        }

        private void Exit() {
            MainWindow.Close();        
        }

        private void SetTempViewFolder() {
            VistaFolderBrowserDialog folderBrowserDialog = new VistaFolderBrowserDialog();
            folderBrowserDialog.ShowDialog();

            if (!string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath))
                this.BackstageViewModel.TemporaryViewPath = folderBrowserDialog.SelectedPath;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        private void OpenInputDialog(object param) {
            List<object> parameters = (List<object>)(param);
            _inputDialog = new Windows.InputDialog(parameters[0].ToString(), parameters[1].ToString(), parameters[2].ToString());
            bool? result = _inputDialog.ShowDialog();
            if (result.Value) {
                switch (((Fluent.Button)(parameters[3])).Name) {
                    case "btnBackstagePreferencesApplicationFoldersBasicResultPathName":
                        this.BackstageViewModel.BasicResultPathName = _inputDialog.DialogContentResult;
                        break;
                    case "btnBackstagePreferencesApplicationFoldersSessionPathName":
                        this.BackstageViewModel.SessionPathName = _inputDialog.DialogContentResult;
                        break;
                    case "btnBackstagePreferencesApplicationFoldersMergePathName":
                        this.BackstageViewModel.MergePathName = _inputDialog.DialogContentResult;
                        break;
                    case "btnBackstagePreferencesApplicationFoldersDocumentsPathName":
                        this.BackstageViewModel.DocumentsPathName = _inputDialog.DialogContentResult;
                        break;
                    case "btnBackstagePreferencesApplicationFoldersTempViewPathName":
                        this.BackstageViewModel.TemporaryViewPath = _inputDialog.DialogContentResult;
                        break;
                    default:
                        break;
                }
               
            }
        }


        #endregion



        #region HelperMethods

        

        #endregion
    }
}
